<?php
if (!defined('__COLA_DIR__')) exit;

/**
 * 当前登录用户
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_User extends Cola
{
    /**
     * 用户
     *
     * @access private
     * @var array
     */
    private $_user;

    /**
     * 是否已经登录
     *
     * @access private
     * @var boolean
     */
    private $_hasLogin = NULL;

    /**
     * 全局选项
     *
     * @access protected
     * @var Widget_Options
     */
    protected $options;

    /**
     * 数据库对象
     *
     * @access protected
     * @var Db
     */
    protected $db;

    /**
     * 用户组
     *
     * @access public
     * @var array
     */
    public $groups = array(
            'admin'         => 0,
            'editor'		=> 1,
            'contributor'	=> 2,
            'member'	    => 3,
            'visitor'		=> 4
    );
	
    /**
     * 构造函数,初始化组件
     *
     * @access public
     * @param mixed $request request对象
     * @param mixed $response response对象
     * @param mixed $params 参数列表
     */
    public function __construct($request, $response, $params = NULL)
    {
        parent::__construct($request, $response, $params);

        /** 初始化数据库 */
        $this->db = Db::instance();
        $this->options = $this->widget('Widget_Options');
		
        $this->groups[0] = array(
            'admin'         => _t('管理员'),
            'editor'		=> _t('编辑员'),
            'contributor'	=> _t('贡献者'),
            'member'	    => _t('注册者'),
            'visitor'		=> _t('访问者')	
		);
		
		/** 插件接口 */
		//HOOK PLUG_User($this);
    }

    /**
     * 执行函数
     *
     * @access public
     * @return void
     */
    public function execute()
    {
        if ($this->hasLogin()) {

            $this->push($this->_user);

            //更新最后活动时间
			($this->options->time - $this->activated) > 100 &&
            $this->db->update('table.users')
                ->values(array('activated'=>$this->options->time))
                ->where('uid = ?', $this->_user['uid'])
			    ->affectedRows();
        }
    }

    /**
     * 以用户名和密码登录
     *
     * @access public
     * @param string $name 用户名或邮箱
     * @param string $password 密码
     * @param boolean $temporarily 是否为临时登录
     * @param integer $expire 过期时间
     * @return boolean
     */
    public function login($name, $password, $temporarily = false, $expire = 0)
    {
		/** 插件接口 */
		//HOOK {$plugged} $result | PLUG_Login($name, $password, $temporarily, $expire);
		
        if ($plugged) {
            return $result;
        }

        /** 开始验证用户 **/
        $user = $this->db->select()
		    ->from('table.users')
            ->where((strpos($name, '@') ? 'mail' : 'name') . ' = ?', $name)
            ->limit(1)
			->fetchRow();

        if (empty($user)) {
            return false;
        }
	
	    /** 插件接口 */
		//HOOK {$plugged} $hashValidate | PLUG_HashValidate($password, $user['password']);
		
        if (!$plugged) {
            $hashValidate = Common::hashValidate($password, $user['password']);
        }

        if ($hashValidate) {
            if (!$temporarily) {
                $salt = sha1(Common::randString(20));
                $user['salt'] = $salt;

                Cookie::set('__cola_uid', $user['uid'], $expire);
                Cookie::set('__cola_salt', Common::hash($salt), $expire);

                //更新验证码 更新最后登录时间
                $this->db->update('table.users')
                    ->values(array('salt' => $salt, 'logged' => $this->options->time))
                    ->where('uid = ?', $user['uid'])
				    ->affectedRows();
            }

            /** 压入数据 */
            $this->push($user);
            $this->_user = $user;
            $this->_hasLogin = true;

			/** 插件接口 */
            //HOOK PLUG_Login_Success($this, $name, $password, $temporarily, $expire);
			
            return true;
        }
		
		/** 插件接口 */
		//HOOK PLUG_Login_Fail($this, $name, $password, $temporarily, $expire);

        return false;
    }
    
    /**
     * 只需要提供uid即可登录的方法, 多用于插件等特殊场合
     * 
     * @access public
     * @param integer $uid 用户id
     * @return boolean
     */
    public function simpleLogin($uid)
    {
        $user = $this->db->select()
		    ->from('table.users')
            ->where('uid = ?', $uid)
            ->limit(1)
			->fetchRow();
        
        if (empty($user)) {
            return false;
        }
        
        $this->push($user);
        $this->_hasLogin = true;
        
        return true;
    }

    /**
     * 用户登出函数
     *
     * @access public
     * @return void
     */
    public function logout()
    {
		/** 插件接口 */
		//HOOK {$plugged} | PLUG_Logout($this);
		
        if ($plugged) {
            return;
        }

        Cookie::delete('__cola_uid');
        Cookie::delete('__cola_salt');
    }

    /**
     * 判断用户是否已经登录
     *
     * @access public
     * @return boolean
     */
    public function hasLogin()
    {
        if (NULL !== $this->_hasLogin) {
            return $this->_hasLogin;
        } else {
            $cookieUid = Cookie::get('__cola_uid');
            if (NULL !== $cookieUid) {
				
                /** 验证登陆 */
                $user = $this->db->select()
				    ->from('table.users')
                    ->where('uid = ?', intval($cookieUid))
                    ->limit(1)
					->fetchRow();

                $cookieAuthCode = Cookie::get('__cola_salt');
                if ($user && Common::hashValidate($user['salt'], $cookieAuthCode)) {
                    $this->_user = $user;
                    return ($this->_hasLogin = true);
                }

                $this->logout();
            }

            return ($this->_hasLogin = false);
        }
    }
	
    /**
     * 判断用户权限
     *
     * @access public
     * @param string $group 用户组
     * @param boolean $return 是否为返回模式
     * @return boolean
     * @throws Widget_Exception
     */
    public function pass($group, $return = false)
    {
        if ($this->hasLogin()) {
            if (array_key_exists($group, $this->groups) && $this->groups[$this->group] <= $this->groups[$group]) {
                return true;
            }
        } else {
            if ($return) {
                return false;
            } else {
                //防止循环重定向
                $this->response->redirect($this->options->loginUrl .
                (0 === strpos($this->request->getReferer(), $this->options->loginUrl) ? '' :
                '?referer=' . urlencode($this->request->makeUriByRequest())), false);
            }
        }

        if ($return) {
            return false;
        } else {
            throw new Widget_Exception(_t('禁止访问'), 403);
        }
    }
    /**
     * 输出用户头像
     *
     * @access public
     * @param integer $size 头像尺寸
     * @param string $rating 头像评级
     * @return void
     */
    public function ___avatar()
    {
		$icon = $this->pic;
		if($icon){
		    strpos($icon, '://') === FALSE && $icon = $this->options->uploadUrl . $icon;
		}else{
			$icon = $this->options->staticUrl('images/avatar-default.png', false);
		}
        return $icon;
    }
}